<?php
/**
 * AJAX Handler for Usernames: Check - Return an ajax call that states if the username exists
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    require_once('../../SiteIncludes.GLOBAL.php');
    
    $return_head = <<<EOHEAD
	<!DOCTYPE html>
	    <html>
	    <head><title></title></head>
	    <body>
		<script type="text/javascript">
EOHEAD;
    $return_nok = 'parent.EDJXConfirmer.show_nok();';
    $return_ok = 'parent.EDJXConfirmer.show_ok();';
    $return_foot = <<<EOFOOT
		</script>
	    </body>
	</html>
EOFOOT;
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	$gVAR['e'] = '404';
	require_once('error_handler.php');
    }
    
    if(isset($gVAR['user']) === true) {
	/**
	 * A-Z a-z 0-9 _ is enforced by apache 
	 * 
	 * Minimum Length: 5
	 * Maximum Length: 14
	 */
	if(strlen($gVAR['user']) < 5) {
	    // too short
	    $return_body = <<<EOBODY
		$return_nok
		parent.NewUser.checkUsername_callback(false, 'Username is too short. It must be at least 5 characters long.');
EOBODY;
	} elseif(strlen($gVAR['user']) > 14) {
	    // too long
	    $return_body = <<<EOBODY
		$return_nok
		parent.NewUser.checkUsername_callback(false, 'Username is too long. It must be at most 14 characters long.');
EOBODY;
	} else {
	    // correct length
	    try {
		$User =& $UserStash->get($gVAR['user']);
		
		// if we get here the user exists already
		$return_body = <<<EOBODY
		    $return_nok
		    parent.NewUser.checkUsername_callback(false, 'Username is already taken.');
EOBODY;
	    } catch(InvalidUserException $e) {
		// if we get here the username is available
		$return_body = <<<EOBODY
		    $return_ok
		    parent.NewUser.checkUsername_callback(true, '');
EOBODY;
	    }
	}
	
    } else {
	$return_body = $return_nok;
    }
    
    
    echo $return_head.$return_body.$return_foot;
?>
